//
//  NetworkTools.swift
//  新浪微博
//
//  Created by yzl on 15/7/30.
//  Copyright © 2015年 yjc. All rights reserved.
//

import UIKit
import AFNetworking

/// MARK : 错误的类别标记
private let ErrorDomainName = "com.itheima.error.network"
 /// 利用枚举封装错误信息 (枚举可以定义函数和类)
private enum networkError:Int {
    case emptyErrorDate = -1
    case emptyTokenDate = -2
/// 错误描述（定义属性）
    private var errorDescription:String {
        switch self {
        case .emptyErrorDate :return "空数据"
        case .emptyTokenDate :return "空Token"
        }
    }
/// 根据枚举类型返回对应错误（定义类方法）
    private func backError() ->NSError {
        return NSError(domain: ErrorDomainName, code: rawValue, userInfo: [ErrorDomainName:errorDescription])
    }
}
 /// MARK : 枚举
private enum networkMethod:String {
    case GET = "GET"
    case POST = "POST"
}


 typealias NetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?)->()

class NetworkTools: AFHTTPSessionManager {
    // MARK:  OAuth授权
    private let clientId = "121422043"
    private let appSecret = "17eaae94394e64b2b7829494fb7d295a"
    /// 回调地址
    let redirectUri = "http://www.baidu.com"
    // 全局访问点
    static let sharedNetworkTools: NetworkTools = {
        let tools = NetworkTools(baseURL: NSURL(string: "https://api.weibo.com/")!)
        // 设置数据，解析数据类型
        tools.responseSerializer.acceptableContentTypes  = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tools
        }()
    
    /// 方法抽取，Token
    private func TokenCrash(finished:NetFinishedCallBack) -> [String: AnyObject]? {
        // 判断 token 是否存在
        if userAccount.shareAccount?.access_token == nil {
            let error = networkError.emptyTokenDate.errorDescription
            print(error)
            return nil
        }
      
        return ["access_token": userAccount.shareAccount!.access_token!]
    }
   
    
    /// 加载微博数据
    func loadstatus(finished:NetFinishedCallBack){
        // 判断 token 是否存在
        guard let params = TokenCrash(finished) else{
            return
        }
        
               let urlString = "2/statuses/home_timeline.json"
        
        request(networkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
   
    
    
    
    /// MARK :加载用户信息
    func loadUserInfo(uid:String,finished:NetFinishedCallBack){
        // 判断 token 是否存在
        guard var  params = TokenCrash(finished) else{
            return
        }

        let urlString = "2/users/show.json"
       params["uid"] = uid
       // print(params)
        
        // 发送网络请求
        // 提示：如果参数不正确，首先用 option + click 确认参数类型
        request(networkMethod.GET, urlString: urlString, params: params, finished: finished)
       
    }
    /// 返回OAuth的授权地址
    func oauthUrl() ->NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    /// 加载TOKen
    func loadAccessToken(code:String,finished: NetFinishedCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id":clientId,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri": redirectUri
        ]
        request(networkMethod.POST, urlString: urlString, params: params, finished:finished)
       
    }
    // MARK: - 封装 AFN 网络方法，便于替换网络访问方法，第三方框架的网络代码全部集中在此
    /// GET/POST 方法
    private func request(Method:networkMethod, urlString: String, params: [String: AnyObject], finished: NetFinishedCallBack){
        // 定义成功闭包
        let success:(NSURLSessionDataTask!,AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finished(result: result, error: nil)
            } else {
                // 没有错误，同时没有结果
                print("没有数据 POST Request \(urlString)")
                
                finished(result: nil, error: networkError.emptyTokenDate.backError())
            }
            
        }
        // 定义失败闭包
        let failed :(NSURLSessionDataTask!,NSError!)->Void =
            { (_, error) -> Void in
                print(error)
                
                finished(result: nil, error: error)
            }
        switch Method {
        case.GET:GET(urlString, parameters: params, success: success, failure: failed)
        case.POST:POST(urlString, parameters: params, success: success, failure: failed)
        }
        
    }
    
//    private func requestPOST(urlString: String, params: [String: AnyObject], finished: NetFinishedCallBack) {
//        
//      POST(urlString, parameters: params, success: { (_, JSON) -> Void in
//            
//            if let result = JSON as? [String: AnyObject] {
//                // 有结果的回调
//                finished(result: result, error: nil)
//            } else {
//     /Volumes/My Passport/swift项目oo/swift项目/05天首页布局/布局框架/FFAutoLayout/Source/UIView+AutoLayout.swift           // 没有错误，同时没有结果
//                print("没有数据 POST Request \(urlString)")
//                
//                /**
//                domain: 错误的范围/大类别，定义一个常量字符串
//                code: 错误代号，有些公司会专门定义一个特别大的.h，定义所有的错误编码，通常是负数
//                userInfo: 可以传递一些附加的错误信息
//                */
//                //                let error = NSError(domain: ErrorDomainName, code: -1, userInfo: ["errorMessage": "空数据"])
//                
//                finished(result: nil, error: networkError.emptyTokenDate.backError())
//            }
//            
//            }) { (_, error) -> Void in
//                print(error)
//                
//                finished(result: nil, error: error)
//        }
//    }
//    
//    
//    
//    
//    
//    
//    
    
   
    
    }
